package com.wmm.service.impl;

import com.wmm.common.Product;
import com.wmm.common.ProductVo;
import com.wmm.mapper.ProductMapper;
import com.wmm.repoistry.EsResultMapper;
import com.wmm.service.ProductService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ElasticsearchTemplate template;


    @Override
    public Product queryById(Integer id) {
        return productMapper.selectById(id);
    }

    @Override
    public Map queryEsByName(ProductVo productVo) {

        Map<String, Object> res = new HashMap<>();

        // 查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 搜索条件
        queryBuilder.withQuery(QueryBuilders.matchQuery("name", productVo.getName()));
        // 过滤条件
        queryBuilder.withFilter(QueryBuilders.rangeQuery("price").
                gte(productVo.getMinPrice()).lte(productVo.getMaxPrice()));
        // 分页及排序条件
        queryBuilder.withPageable(
                PageRequest.of(productVo.getPage(), 5, Sort.by(Sort.Direction.ASC, "price")));
        // 内容高亮显示
        HighlightBuilder.Field field = new
                HighlightBuilder.Field("name").preTags("<font style='color:red'>").postTags("</font>");
        queryBuilder.withHighlightFields(field);

        // 构建查询条件，并且查询
        AggregatedPage<Product> result = template.queryForPage(queryBuilder.build(), Product.class, new EsResultMapper());
        res.put("total", result.getTotalElements());
        res.put("totalPages", result.getTotalPages());
        res.put("list", result.getContent());
        return res;
    }
}
